package com.pan.tools;

import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class ConvertObject {

    public static Object convertObject(Class newObjectClass,Object oldObject){
        Class oldClass = oldObject.getClass();
        Field[] oldFields = oldClass.getDeclaredFields();
        Field[] newFields = newObjectClass.getDeclaredFields();
        Object newObject;
        try {
            newObject = newObjectClass.newInstance();
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        Map<String,Class> oldMap = Arrays.stream(oldFields)
                .collect(Collectors.toMap(Field::getName,Field::getType));
        Arrays.stream(newFields).forEach(field -> {
            String memberName = field.getName();
            Class memberType = field.getType();
            if (oldMap.get(memberName) == memberType){
                try {
                    Field oldField = oldClass.getDeclaredField(memberName);
                    oldField.setAccessible(true);
                    Object value = oldField.get(oldObject);
                    field.setAccessible(true);
                    field.set(newObject,value);
                } catch (NoSuchFieldException e) {
                    throw new RuntimeException(e);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        return newObject;
    }


}
